package com.mensanyun.yminder.core.data

import java.util.*

class Sheet(val uid: String, var title: String) {
     var primaryTopic: Topic = defaultTopic()
    private val topics = mutableMapOf<String, Topic>()
    private val connections = mutableMapOf<String, Connection>()


    init {
        topics[primaryTopic.uid] = primaryTopic
    }


    fun addSiblingTopic(siblingId: String) {

        require(topics.containsKey(siblingId))

        topics[siblingId]?.let {
            val topic = defaultTopic()
            topics[topic.uid] = topic
            it.parentId?.let { parentId ->
                topics[parentId]?.also { parentTopic ->
                    parentTopic.addSubTopic(topic)
                    connectTopics(parentId, topic.uid)
                }
            }
        }
    }


    fun addSubTopic(parentId: String) {
        require(topics.containsKey(parentId))
        topics[parentId]?.let {
            val topic = defaultTopic()
            topic.parentId = it.uid
            topics[topic.uid] = topic
            it.addSubTopic(topic)
            connectTopics(parentId, topic.uid)
        }
    }

    private fun connectTopics(from: String, to: String) {
        topics[from]?.let {
            topics[to]?.let {
                val connection = Connection(UUID.randomUUID().toString(), from, to)
                connections[connection.uid] = connection
            }
        }
    }

    fun addConnection(connection: Connection) {
        connections[connection.uid] = connection
    }

    fun topics(): List<Topic> {
        return topics.values.toList()
    }

    fun connections(): List<Connection> {
        return connections.values.toList()
    }


    fun addFreeTopic(title: String): Topic {
        val topic = defaultTopic(title)
        topics[topic.uid] = topic
        return topic
    }

    private fun defaultTopic(text: String = "Input Text"): Topic {
        return Topic(UUID.randomUUID().toString(), text)
    }

}